package com.yuji.aacar.net.convertfactory;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.net.bean.HttpCoreBaseRequest;
import com.yuji.aacar.net.bean.HttpCoreRequestHeader;
import com.yuji.aacar.net.config.HttpConfig;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * <li>Package:consumer.ttpc.com.httpmodule.converterfactory
 * <li>Author: yehaijian
 * <li>Date: 2017/6/6
 * <li>Description: 无网络加密的post请求转换， 新增了code服务编码
 */
public class JsonNoSecretRequestConverter<T> extends JsonRequestBodyConverter<T>{

    /**
     * 构造器
     *
     * @param gson
     * @param adapter
     * @param code
     */
    public JsonNoSecretRequestConverter(Gson gson, TypeAdapter adapter, int code) {
        super(gson, adapter, code);
    }

    @Override
    public RequestBody convert(T value) throws IOException {
        int code=0;
        if(value instanceof HttpCoreBaseRequest){
            code=this.code!=0?this.code:((HttpCoreBaseRequest) value).getRequestCode();
        }
        HttpCoreRequestHeader head = new HttpCoreRequestHeader(code);
        //将最终bean生成json串
        String bodyJson = gson.toJson(value, new TypeToken<T>() {
        }.getType());
//        Gson g = new GsonBuilder().serializeNulls().create();
        String headerJson = gson.toJson(head, new TypeToken<HttpCoreRequestHeader>() {
        }.getType());
        LogUtil.e("request", "request body## ：" + code + " " + bodyJson);
        LogUtil.e("request", "request header## ：" + code + " " + headerJson);


        FormBody.Builder builder = new FormBody.Builder();
        FormBody formBody =value instanceof HttpCoreBaseRequest ?
                builder.add("info", bodyJson).add("mobilehead",headerJson).add(HttpConfig.IS_WEBVIEW,((HttpCoreBaseRequest)value).isWebView()+"")
                        .build():
                builder.add("info", bodyJson).add("mobilehead",headerJson)
                        .build();
        return formBody;
    }
}
